﻿/****************************************************************
  Author:  Ievgenii Nazaruk, ievgenii.nazaruk@gmail.com 
 License:  Microsoft Public License (Ms-PL)
          ( http://www.opensource.org/licenses/ms-pl.html or
            http://www.microsoft.com/opensource/licenses.mspx )
*****************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebLayer;

namespace WebPageParser
{
    /// <summary>
    /// WebPageCache is class which stores already received web-pages
    /// so no extra work is done.
    /// </summary>
    public class WebPageCache
    {
        Dictionary<Type, SiteWebPage> WebPages = new Dictionary<Type,SiteWebPage>();
        LoginToken m_loginToken = null;
        public LoginToken LoginToken
        {
            set
            {
                foreach(SiteWebPage page in WebPages.Values)
                {
                    page.LoginToken = value;
                }
                m_loginToken = value;
            }
            get
            {
                return m_loginToken;
            }
        }

        public PageType GetPage<PageType>() where PageType : SiteWebPage, new()
        {
            if(WebPages.Keys.Contains(typeof(PageType)) )
            {
                return (PageType)WebPages[typeof(PageType)];
            }
            
            PageType newPage = new PageType();
            newPage.LoginToken = LoginToken;
            newPage.Request();

            WebPages[typeof(PageType)] = newPage;
            return newPage;
        }

        public void DiscardPage<PageType>() where PageType : SiteWebPage
        {
            if (WebPages.Keys.Contains(typeof(PageType)) == true)
            {
                WebPages.Remove(typeof(PageType));
            }
        }

        public void Discard()
        {
            WebPages = new Dictionary<Type, SiteWebPage>();
        }        
    }
}
